package com.fy.springcloud.controller;

import com.fy.springcloud.controller.feign.EchoServiceFeign;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.client.ServiceInstance;
import org.springframework.cloud.client.discovery.DiscoveryClient;
import org.springframework.cloud.client.loadbalancer.LoadBalancerClient;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.client.RestTemplate;

import javax.annotation.Resource;

@RestController
public class TestController {

    @Autowired
    private LoadBalancerClient loadBalancerClient;

    @Autowired
    private RestTemplate restTemplate;

    @Autowired
    private DiscoveryClient discoveryClient;

    @Resource
    private EchoServiceFeign echoServiceFeign;

    @GetMapping("/echo/{app}")
    public String echoAppName(@PathVariable("app") String app) {
        ServiceInstance serviceInstance = loadBalancerClient.choose("nacos-discovery-provider");
        String url = String.format("http://%s:%s/echo/%s", serviceInstance.getHost(), serviceInstance.getPort(), app);
        System.out.println("request url: " + url);
        return restTemplate.getForObject(url, String.class);
    }

    @GetMapping("/echo-rest/{str}")
    public String echoRest(@PathVariable String str) {
        return restTemplate.getForObject("http://nacos-discovery-provider/echo/" + str, String.class);
    }

    @GetMapping("/notFound-feign")
    public String notFound() {
        return echoServiceFeign.notFound();
    }

    @GetMapping("/divide-feign")
    public String divide(@RequestParam Integer a, @RequestParam Integer b) {
        return echoServiceFeign.divide(a, b);
    }

    @GetMapping("/divide-feign2")
    public String divide(@RequestParam Integer a) {
        return echoServiceFeign.divide(a);
    }

    @GetMapping("/echo-feign/{str}")
    public String echoFeign(@PathVariable String str) {
        return echoServiceFeign.echo(str);
    }

    @GetMapping("/services/{service}")
    public Object client(@PathVariable String service) {
        return discoveryClient.getInstances(service);
    }

    @GetMapping("/services")
    public Object services() {
        return discoveryClient.getServices();
    }
}
